package org.example.aienglishapp.util.debounce;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author xlj
 * @since 2024-10-1
 * @version 1.0
 */
public class DebounceUtil {

    private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(10);
    private static final ConcurrentHashMap<String, AtomicBoolean> debounceMap = new ConcurrentHashMap<>();

    public static void debounce(String key, Runnable task, long delay, TimeUnit unit) {
        debounceMap.putIfAbsent(key, new AtomicBoolean(false));
        AtomicBoolean running = debounceMap.get(key);

        if (running.compareAndSet(false, true)) {
            scheduler.schedule(() -> {
                try {
                    task.run();
                } finally {
                    running.set(false);
                }
            }, delay, unit);
        }
    }
}